<?php
namespace Hive\Ressource;
/**
 * Address Link
 * 
 * This class maintain the link between adresses and ressources, it is a valued link 
 * and define the type of address
 */
class Address extends \Fox\Object {
	/**
	 * Link to Contact
	 * @var string
	 */
	const LINK_RESSOURCE = 'ressource';
	
	/**
	 * 
	 * Reverse Link for real Addresses
	 * @var string
	 */
	const LINK_RESSOURCE_ADDRESS = 'ressourceAddress';
	
	/**
	 * Link to real address object
	 * @var string
	 */
	const LINK_ADDRESS = 'address';

	/**
	 * Reference Professional
	 * @var string
	 */
	const REFERENCE_PROFESSIONAL = 3;
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::afterCreate()
	 */
	protected function beforeCreate() {
		$address = $this->address();
		$adrid = $address->adrid;
		if(!$address->exists() && empty($adrid)) {
			$address->create();
		}
		$this->adrid = $address->adrid;
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::afterCreate()
	 */
	protected function afterCreate() {
		// Add to the search engine
		$searchEngine = new \Fox\SearchEngine();
		$address = $this->address();
		$searchEngine->synchronize($address,$this->ressource_id,\Hive\Ressource::className());
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::afterCreate()
	 */
	protected function afterUpdate() {
		$this->address()->update();
		$address = $this->address();
		// Add to the search engine
		$searchEngine = new \Fox\SearchEngine();
		$searchEngine->synchronize($address,$this->ressource_id,\Hive\Ressource::className());
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::beforeUpdate($changed)
	 */
	protected function beforeUpdate($changed) {
		if($this->address()->changed()) {
			$changed = true;
		}
		return $changed;
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::afterSetFields($fields)
	 */
	public function afterSetFields(array $fields) {
		unset($fields['adrid']);
		$this->address()->setFields($fields);
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Fox\Object\Versioned::delete()
	 */
	public function delete()
	{
		$handle = \Fox\Dao::infos(self::className())->handle();
		$handle->beginTransaction();
		$address = $this->address();
		// Remove All Search Help matches
		$searchEngine = new \Fox\SearchEngine();
		$searchEngine->deleteMatchesByReference($address);
		$address->delete();
		parent::delete();
		$handle->commit();
	}
}
\Fox\Dao::infos(Address::className(),new \Fox\Object\Info('ressource_addresses', \Fox\Databases::DB_APP));

// Link to Document
\Fox\Object\Links::add(\Fox\Dao::link(Address::className(),Address::LINK_ADDRESS)
	->to(\Fox\Common\Address::className(),Address::LINK_RESSOURCE_ADDRESS)
	->on('adrid')
	->oneToOne()
	);